package com.itheima.service.OperationImpl;

import com.itheima.dao.OperationDao;
import com.itheima.domain.Option;
import com.itheima.service.PrintLogDao;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.util.List;

public class PrintLogDaoImpl implements PrintLogDao {
    private OperationDao operationDao;

    public void setOperationDao(OperationDao operationDao) {
        this.operationDao = operationDao;
    }

    @Override
    public ByteArrayOutputStream getReport() throws Exception {
        List<Option> stuInfo = operationDao.findAll();
        Workbook wb = new XSSFWorkbook();

        Sheet sheet = wb.createSheet("题目数据文件");
        for (int i = 1; i < 16; i++) {
            sheet.setColumnWidth(i,40*256);
        }

        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);


        sheet.addMergedRegion(new CellRangeAddress(1,1,1,4));
        Row row = sheet.createRow(1);
        Cell cell = row.createCell(1);
        cell.setCellValue("在线日志导出信息");


        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        cell.setCellStyle(style);
        //制作表头,准备表头数据对应的数组
        String[] info = {"操作时间","操作的类和方法","方法参数","返回值"};
        //创建行
        Row row2 = sheet.createRow(2);

        for (int i = 0; i < info.length; i++) {

            Cell cells = row2.createCell(i + 1);

            cells.setCellValue(info[i]);

            cells.setCellStyle(cs_field);
        }



        int row3 = 3;
        for (Option option : stuInfo) {
            Row sheetRow = sheet.createRow(row3);
            Field[] fields = option.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                String value = (String)fields[i].get(option);
                sheetRow.createCell(i+1).setCellValue(value);
            }
            row3++;
        }


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);

        wb.close();
        return baos;


    }
}
